package chapter15;

import java.util.Arrays;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/14 16:21
 */
public class GenericReading {
    static <T> T readExact(List<T> list){
        return list.get(0);
    }

    static List<Apple> apples = Arrays.asList(new Apple());
    static List<Fruit> fruits = Arrays.asList(new Fruit());

    static void f1(){
        Apple apple = readExact(apples);
        Fruit fruit = readExact(fruits);
        fruit = readExact(apples);
    }

    static class Reader<T>{
        T readExact(List<T> list){
            return list.get(0);
        }
    }

    static void f2(){
        Reader<Fruit> fruitReader = new Reader<>();
        Fruit fruit = fruitReader.readExact(fruits);
        // error:
        //Fruit appple = fruitReader.readExact(apples);
    }

    static class CovariantReader<T>{
        T readCovariant(List<? extends T> list) {
            return list.get(0);
        }
    }

    static void f3(){
        CovariantReader<Fruit> fruitReader = new CovariantReader<>();
        Fruit fruit = fruitReader.readCovariant(fruits);
        Fruit apple = fruitReader.readCovariant(apples);
    }

    public static void main(String[] args) {
        f1();
        f2();
        f3();
    }
}
